
 #!/usr/bin/python

#pgrep -flu postgres SELECT
#ps -o pid,ppid,rss,vsize,pcpu,pmem,cmd -ww --sort=pid -p 18541

# a.  Memory Used
# b.  Memory Used - Memory Buffers - Memory Cached
# c.  Swap Used

# faheem@avicenna:~$ free -o
# total       used       free     shared    buffers     cached
# Mem:      66115440   34571680   31543760          0     468280   28317348
# Swap:    124997624     245016  124752608

import commands, os

def pid(getoutput_str):
    return commands.getoutput(getoutput_str).split()[0]

def header(getoutput_str):
    try:
        pid = commands.getoutput(getoutput_str).split()[0]
        print pid
        meminfo = commands.getoutput("ps -o pid,ppid,rss,vsize,pmem,cmd -ww --sort=pid -p "+ pid)
        print meminfo.split('\n')[0]
        return meminfo.split('\n')[1].split()[:5]
    except:
        pass

def meminfo(getoutput_str):
    try:
        pid = commands.getoutput(getoutput_str).split()[0]
        meminfo = commands.getoutput("ps -o pid,ppid,rss,vsize,pmem,cmd -ww --sort=pid -p "+ pid)
        return meminfo.split('\n')[1].split()[2:5]
    except:
        pass

def write_to_file(getoutput_str, filename=None):
    import os, time
    header = ["time", "RSS", "VSZ", "%MEM"]
    header = ','.join(header)+'\n'
    t = 0
    m = meminfo(getoutput_str)
    if m != None:
        if filename==None:
            p = pid(getoutput_str)
            filename = "meminfo_%s.csv"%p
        f = open(filename, 'w')
        f.write(header)
    while True:
        m = meminfo(getoutput_str)
        if m == None:
            break
        else:
            t+=1
            m = [str(t)] + m
            m = ','.join(m)+'\n'
            f.write(m)
            f.flush()
        time.sleep(1)
    print "closing file"
    f.close()
    os.system("Rscript memgraph.R %s"%filename)

import sys, traceback
from optparse import OptionParser
usage = "usage is of the form '%prog filename'\n"
parser = OptionParser(usage=usage)
#parser.add_option("-c", "--map-col", action="store_true", dest="mapcol", help="add column to map file")
(options, args) = parser.parse_args()
if len(args) < 1:
    print "incorrect number of arguments"
    parser.print_help()
    sys.exit()

filename = args[0]
getoutput_str = "pgrep -flu postgres SELECT"
#getoutput_str = "pgrep -flu postgres EXPLAIN"
write_to_file(getoutput_str, filename)

# matplotlib.pyplot.plotfile(fname, cols=(0, ), plotfuncs=None,
# comments='#', skiprows=0, checkrows=5, delimiter=', ', names=None,
# subplots=True, newfig=True, **kwargs)

# Plot the data in fname

# cols is a sequence of column identifiers to plot. An identifier is either an int or a string. If it is an int, it indicates the column number. If it is a string, it indicates the column header. matplotlib will make column headers lower case, replace spaces with underscores, and remove all illegal characters; so 'Adj Close*' will have name 'adj_close'.

# * If len(cols) == 1, only that column will be plotted on the y axis.

# * If len(cols) > 1, the first element will be an identifier for data
#   for the x axis and the remaining elements will be the column indexes
#   for multiple subplots if subplots is True (the default), or for
#   lines in a single subplot if subplots is False.

# plotfuncs, if not None, is a dictionary mapping identifier to an Axes
# plotting function as a string. Default is 'plot', other choices are
# 'semilogy', 'fill', 'bar', etc. You must use the same type of
# identifier in the cols vector as you use in the plotfuncs dictionary,
# eg., integer column numbers in both or column names in both. If
# subplots is False, then including any function such as 'semilogy' that
# changes the axis scaling will set the scaling for all columns.

# comments, skiprows, checkrows, delimiter, and names are all passed on
# to matplotlib.pylab.csv2rec() to load the data into a record array.

# If newfig is True, the plot always will be made in a new figure; if
# False, it will be made in the current figure if one exists, else in a
# new figure.

# kwargs are passed on to plotting functions.

# Example usage:

# # plot the 2nd and 4th column against the 1st in two subplots
# plotfile(fname, (0,1,3))

# # plot using column names; specify an alternate plot type for volume
# plotfile(fname, ('date', 'volume', 'adj_close'),
# plotfuncs={'volume': 'semilogy'})


